package com.ybg.share.schedule;


import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.ybg.framework.dto.AbstractJob;
import com.ybg.share.core.dbapi.entity.ShareStock;
import com.ybg.share.core.dbapi.service.ShareStockService;
import com.ybg.share.core.spider.StockProcessor;
import com.ybg.share.utils.ThreadUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.Spider;

import java.math.BigDecimal;


/**
 * 拉取股票定时任务
 */
@Component
@Slf4j
public class StockJob {


    @Autowired
    private ShareStockService shareStockService;



    /**
     * 拉取个股列表(东方财富)
     * {@link StockJob#updateStockDataByWangyi()}
     */
    @Scheduled(cron = "0 30 2 * * ?")
    public void updateStockData() {
        if (false) {
            return;
        }



        StockProcessor stockProcessor = new StockProcessor();
        stockProcessor.setShareStockService(shareStockService);
        try {

            Spider thread = Spider.create(stockProcessor)
                    .addUrl(StockProcessor.STOCK_LIST)

                    .thread(100);

            thread.run();

        } catch (Exception e) {
            log.info("error{}", e);
        } finally {

        }

    }

    /**
     * 拉取股票数据其他字段（网易）
     * http://quotes.money.163.com/old/#query=GSZL&DataType=gszl&sort=ITPROFILE21&order=asc&count=25&page=0
     *
     */
      @Scheduled(cron = "0 30 2 * * ?")
    public void updateStockDataByWangyi() {

        try {
            int page=0;
            String getTotalPageNum=getResult(page);
            JSONObject jsonObject = JSONObject.parseObject(getTotalPageNum);
            Integer pagecount = jsonObject.getInteger("pagecount");
            for(int i=0;i<pagecount;i++){
                String pageResult=getResult(page);
                JSONObject pageJson = JSONObject.parseObject(pageResult);
                JSONArray jsonArray = pageJson.getJSONArray("list");
                for (int j = 0; j < jsonArray.size(); j++) {

                    ThreadUtil.execute(new AbstractJob(jsonArray.getJSONObject(j)) {
                        @Override
                        public void execute() {
                            JSONObject jsobObject= (JSONObject) getParams();
                            String tel = jsobObject.getString("ITPROFILE26");
                            String symbol= jsobObject.getString("SYMBOL");
                            String companyName= jsobObject.getString("COMPANYNAME");
                            BigDecimal registeredCapital= jsobObject.getBigDecimal("ITPROFILE21");//注册资本
                            String cindustry= jsobObject.getString("CINDUSTRY2");//所属行业
                            ShareStock byCode = shareStockService.getByCode(symbol);
                            if(byCode==null){
                                //todo  应该提示记录下来没有这个股票
                               return ;
                            }
                            byCode.setCindustry(cindustry);
                            byCode.setTel(tel);
                            byCode.setRegisteredCapital(registeredCapital);
                            byCode.setCompanyName(companyName);
                            shareStockService.updateById(byCode);
                        }
                    });




                }
                page++;
            }

        } catch (Exception e) {
            log.info("error{}", e);
        } finally {

        }
    }


    private String getResult(int page) {
        ThreadLocal<Integer> maxRerrtTime = new ThreadLocal<>();
        if (maxRerrtTime.get() == null) {
            //最多重试10次
            maxRerrtTime.set(10);
        }

        if (maxRerrtTime.get() == 0) {
            return null;
        }
        try {
            String result = getUrlResult(page);
            return result;
        } catch (Exception e) {
            log.info("error{}", e);
        }
        //如果失败 进行重试
        maxRerrtTime.set(maxRerrtTime.get() - 1);
        return getUrlResult(page);
    }

    private String getUrlResult(int page) {
        String url = "http://quotes.money.163.com/hs/marketdata/service/gszl.php?page=" + page + "&fields=NO,SYMBOL,SNAME,COMPANYNAME,ITPROFILE21,ITPROFILE26,CINDUSTRY2,CODE&sort=SYMBOL&order=asc&count=25&type=query";
        String result = HttpUtil.get(url);
        if (StrUtil.isBlank(result)) {
            return null;
        }
        return result;
    }


}
